﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO;


// Hiển thị và xử lý màn hình Title
namespace MyGames
{
    static public class TitleScreen
    {
        public enum TitleScreenState
        {
            Title,
            NewGamePrompt,
            DifficultChoose,
            NewGame,
            ContinueErr,
            Continue,
            SaveGame,
            Options,
            Help,
            Credits,
            QuitPrompt,
            Quit
        };

        static public TitleScreenState State;
        static public float Difficult;

        #region Declaration
        static Texture2D mainScreen;
        static Texture2D next;
        static Texture2D spark;
        static Texture2D dandelion;

        static SpriteFont menuItemFont;
        static SpriteFont titleFont;
        static Color normalColor;
        static Color selectedColor;
        static Color oldNormalColor;
        static Color oldSelectedColor;

        static List<FlyingObject> flyingObjs;
        static float timer;
        static string[] menuItems;
        static int currentItem = 0;

        static Control btn_next;
        static Control btn_prev;
        static Control btn_text;
        static Control btn_Cancel;
        static Control btn_OK;
        static Control btn_hard;
        static Control btn_normal;
        static Control btn_easy;
        static Control btn_volum;
        static Control btn_back;

        static Control btn_selected;

        static string[] credits;
        static float creditsDelay = 2f;
        static float creditsTimer;
        static int currentCreditsItem = 0;
        static float alpha = 0f;
        static bool stateChanged;
        static int volum = 100;
        #endregion

        #region Initalize
        static public void InitTitleScreen()
        {
            ContentManager content = GameLoader.Content;

            string path = Const.TexturePathGUI + "TitleScreen\\";
            mainScreen = content.Load<Texture2D>(path + "Screen");
            next = content.Load<Texture2D>(path + "Next");
            spark = content.Load<Texture2D>(path + "Spark");
            dandelion = content.Load<Texture2D>(path + "Dandelion");

            menuItemFont = Fonts.MenuFont;
            titleFont = Fonts.TitleFont;
            oldNormalColor = Color.White;
            oldSelectedColor = Color.ForestGreen;

            flyingObjs = new List<FlyingObject>();
            ChangeState(TitleScreenState.Title);
            UpdateMenuItem();

            btn_next = new Control(next, new Vector2(450, 100), 0.9f);
            btn_prev = new Control(next, new Vector2(300, 100), 0.9f);
            btn_text = new Control(menuItems[currentItem], new Vector2(340, 100), 100, next.Height, 1f);
            btn_OK = new Control("OK", new Vector2(280, 160), 100, 30, 1f);
            btn_Cancel = new Control("Cancel", new Vector2(400, 160), 100, 30, 1f);
            btn_easy = new Control("Easy", new Vector2(250, 160), 100, 30, 1f);
            btn_normal = new Control("Normal", new Vector2(350, 160), 100, 30, 1f);
            btn_hard = new Control("Hard", new Vector2(450, 160), 100, 30, 1f);
            btn_volum = new Control("Sound volume: ", new Vector2(340, 120), 140, 30, 1f);
            btn_back = new Control("Back", new Vector2(350, 150), 100, 30, 1f);

            credits = new string[]
            {
                "Story: Aeroblytos http://www.TCOcampaign.com",
                "Vector resource: http://www.fordesigner.com",
                "Sprite resource: http://www.spriter-resource.com",
                "Sprite resource: http://sdb.drshnaps.com",
                "Particle effect: http://rpgmaker.net",
                "Skill effect: http://rpgmaker.net",
                "THANKS FOR PLAYING"
            };
        }
        #endregion

        #region Update
        static private void ChangeState(TitleScreenState state)
        {
            if (state == TitleScreenState.NewGamePrompt || state == TitleScreenState.QuitPrompt)
                btn_selected = btn_OK;
            else if (state == TitleScreenState.DifficultChoose)
                btn_selected = btn_normal;
            else if (state == TitleScreenState.Credits)
                currentCreditsItem = 0;
            else if (state == TitleScreenState.Options)
                btn_selected = btn_back;

            alpha = 0f;
            stateChanged = true;
            State = state;
        }

        static public void UpdateMenuItem()
        {
            currentItem = 0;
            //AudioManager.PushMusic("TitleScreen", true);

            switch (TCOGame.GameState)
            {
                case GameState.Pause:
                    menuItems = new string[] { "Resume", "Save Game", "New Game", "Options", "Help", "Credits", "Quit" };
                    break;

                case GameState.TitleScreen:
                    menuItems = new string[] { "Continue", "New Game", "Options", "Help", "Credits", "Quit" };
                    break;
            }
        }

        static public void Update(GameTime gameTime)
        {
            #region General
            // Remove and update
            for (int i = 0; i < flyingObjs.Count; i++)
            {
                if (!flyingObjs[i].Enabled)
                {
                    flyingObjs.RemoveAt(i);
                    continue;
                }

                flyingObjs[i].Update(gameTime);
            }

            // Add new objects
            timer -= (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (timer <= 0)
            {
                flyingObjs.Add(new FlyingObject(dandelion));
                flyingObjs.Add(new FlyingObject(spark));

                timer = (float)RandomHelper.rand.NextDouble();
            }
            #endregion

            string path = "SaveGame\\save.bin";
            alpha = Math.Min(alpha + 0.05f, 1f);
            normalColor = oldNormalColor * alpha;
            selectedColor = oldSelectedColor * alpha;

            switch (State)
            {
                #region TitleScreen
                case TitleScreenState.Title:
                    {
                        // Return (quit)
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn))
                        {
                            ChangeState(TitleScreenState.QuitPrompt);
                            //AudioManager.PlayCue("Cancel");
                        }

                        // Nagivate
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateRight) ||
                            InputManager.IsButtonClicked(btn_next.ButtonRectangle))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            currentItem++;
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateLeft) ||
                            InputManager.IsButtonClicked(btn_prev.ButtonRectangle))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            currentItem--;
                        }

                        // Select
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) ||
                            InputManager.IsButtonClicked(btn_text.ButtonRectangle))
                        {
                            //AudioManager.PlayCue("Select");

                            switch (menuItems[currentItem])
                            {
                                // TCOGame: Continue Game
                                case "Continue":
                                    if (GameLoader.CheckSaveFileExist()) ChangeState(TitleScreenState.Continue);
                                    else ChangeState(TitleScreenState.ContinueErr);
                                    break;

                                // TCOGame: New Game
                                case "New Game":
                                    if (GameLoader.CheckSaveFileExist()) ChangeState(TitleScreenState.NewGamePrompt);
                                    else ChangeState(TitleScreenState.DifficultChoose);
                                    break;

                                // TCOGame: Resume Game
                                case "Resume":
                                    //AudioManager.PopMusic();
                                    TCOGame.GameState = GameState.Playing;
                                    break;

                                // TCOGame: Save Game
                                case "Save Game":
                                    ChangeState(TitleScreenState.SaveGame);
                                    break;

                                case "Options":
                                    ChangeState(TitleScreenState.Options);
                                    break;

                                case "Help":
                                    ChangeState(TitleScreenState.Help);
                                    break;

                                case "Credits":
                                    ChangeState(TitleScreenState.Credits);
                                    break;

                                case "Quit":
                                    ChangeState(TitleScreenState.QuitPrompt);
                                    break;
                            }
                        }

                        currentItem = (int)MathHelper.Clamp(currentItem, 0, menuItems.Length - 1);
                        break;
                    }
                #endregion

                #region NewGamePrompt
                case TitleScreenState.NewGamePrompt:
                    {
                        // Return
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn))
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Cancel");
                        }

                        // Navigate
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateLeft))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            btn_selected = btn_OK;
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateRight))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            btn_selected = btn_Cancel;
                        }

                        // Select
                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_OK) ||
                            InputManager.IsButtonClicked(btn_OK.ButtonRectangle))
                        {
                            ChangeState(TitleScreenState.DifficultChoose);
                            //AudioManager.PlayCue("Select");
                        }

                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_Cancel) ||
                            InputManager.IsButtonClicked(btn_Cancel.ButtonRectangle))
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Cancel");
                        }

                        break;
                    }
                #endregion

                #region DifficultChoose
                case TitleScreenState.DifficultChoose:
                    {
                        // Nagivate
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateLeft))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            if (btn_selected == btn_hard) btn_selected = btn_normal;
                            else btn_selected = btn_easy;
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateRight))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            if (btn_selected == btn_easy) btn_selected = btn_normal;
                            else btn_selected = btn_hard;
                        }

                        // Select
                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_easy) ||
                            InputManager.IsButtonClicked(btn_easy.ButtonRectangle))
                        {
                            //AudioManager.PlayCue("Select");
                            ChangeState(TitleScreenState.NewGame);
                            Difficult = 0.6f;
                        }
                        else if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_normal) ||
                            InputManager.IsButtonClicked(btn_normal.ButtonRectangle))
                        {
                            //AudioManager.PlayCue("Select");
                            ChangeState(TitleScreenState.NewGame);
                            Difficult = 1f;
                        }
                        else if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_hard) ||
                            InputManager.IsButtonClicked(btn_hard.ButtonRectangle))
                        {
                            //AudioManager.PlayCue("Select");
                            ChangeState(TitleScreenState.NewGame);
                            Difficult = 1.5f;
                        }
                        break;
                    }
                #endregion

                #region ContinueErr
                case TitleScreenState.ContinueErr:
                    {
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn) ||
                            InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) ||
                            InputManager.Gestures.Count > 0)
                        {
                            //AudioManager.PlayCue("Cancel");
                            ChangeState(TitleScreenState.Title);
                        }

                        break;
                    }
                #endregion

                #region QuitPrompt
                case TitleScreenState.QuitPrompt:
                    {
                        // Return
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn))
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Cancel");
                        }

                        // Navigate
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateLeft))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            btn_selected = btn_OK;
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateRight))
                        {
                            //AudioManager.PlayCue("Nagivate");
                            btn_selected = btn_Cancel;
                        }

                        // Select
                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_OK) ||
                            InputManager.IsButtonClicked(btn_OK.ButtonRectangle))
                        {
                            ChangeState(TitleScreenState.Quit);
                            //AudioManager.PlayCue("Select");
                        }

                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_Cancel) ||
                            InputManager.IsButtonClicked(btn_Cancel.ButtonRectangle))
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Cancel");
                        }

                        break;
                    }
                #endregion

                #region Credits
                case TitleScreenState.Credits:
                    {
                        creditsTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                        if (creditsTimer >= creditsDelay)
                        {
                            creditsTimer = 0;
                            currentCreditsItem++;
                            if (!(currentCreditsItem == credits.Length)) alpha = 0f;
                            currentCreditsItem = Math.Min(currentCreditsItem, credits.Length - 1);
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn) ||
                            InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) ||
                            InputManager.IsLeftMouseTriggered() ||
                            InputManager.Gestures.Count > 0)
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Cancel");
                        }

                        break;
                    }
                #endregion

                #region Options
                case TitleScreenState.Options:
                    {
                        // Return
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn))
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Nagivate");
                        }

                        // Navigate
                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateUp))
                        {
                            btn_selected = btn_volum;
                            //AudioManager.PlayCue("Nagivate");
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateDown))
                        {
                            btn_selected = btn_back;
                            //AudioManager.PlayCue("Nagivate");
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateLeft) && btn_selected == btn_volum)
                        {
                            volum = Math.Min(volum - 5, 100);
                            //AudioManager.PlayCue("Click");
                        }

                        if (InputManager.IsActionTriggered(InputManager.Action.NagivateRight) && btn_selected == btn_volum)
                        {
                            volum = Math.Min(volum + 5, 100);
                            //AudioManager.PlayCue("Click");
                        }

                        // Select
                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_back) ||
                            InputManager.IsButtonClicked(btn_back.ButtonRectangle))
                        {
                            ChangeState(TitleScreenState.Title);
                            //AudioManager.PlayCue("Cancel");
                        }

                        if ((InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) && btn_selected == btn_volum) ||
                            InputManager.IsButtonClicked(btn_volum.ButtonRectangle))
                        {
                            btn_selected = btn_volum;
                            //AudioManager.PlayCue("Nagivate");
                        }

                        break;
                    }
                #endregion

                #region Help

                case TitleScreenState.Help:
                    if (InputManager.IsActionTriggered(InputManager.Action.NagivateReturn) ||
                        InputManager.IsActionTriggered(InputManager.Action.NagivateSelect) ||
                        InputManager.IsLeftMouseTriggered() ||
                        InputManager.Gestures.Count > 0)
                    {
                        ChangeState(TitleScreenState.Title);
                        //AudioManager.PlayCue("Cancel");
                    }
                    break;

                #endregion

                default:
                    break;
            }
        }
        #endregion

        #region Draw
        static public void Draw(SpriteBatch spriteBatch)
        {
            // Background
            spriteBatch.Draw(mainScreen, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0.1f);
            foreach (FlyingObject obj in flyingObjs)
                obj.Draw(spriteBatch);

            // Title
            Fonts.DrawCenteredText(spriteBatch, titleFont, "The Chosen One", new Vector2(400, 50), oldNormalColor);

            if (stateChanged)
            {
                stateChanged = false;
                return;
            }

            // Specific texts
            switch (State)
            {
                #region TitleScreen
                case TitleScreenState.Title:
                    {
                        // Menu items
                        btn_next.Draw(spriteBatch, menuItemFont, normalColor, SpriteEffects.FlipHorizontally);
                        btn_prev.Draw(spriteBatch, menuItemFont, normalColor, SpriteEffects.None);

                        btn_text.Text = menuItems[currentItem];
                        btn_text.Draw(spriteBatch, menuItemFont, normalColor, SpriteEffects.None);
                        break;
                    }
                #endregion

                #region NewGamePrompt
                case TitleScreenState.NewGamePrompt:
                    {
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "All your old saved game will be deleted.", new Vector2(400, 100), normalColor);
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "Are you sure?", new Vector2(400, 120), normalColor);

                        btn_OK.Draw(spriteBatch, menuItemFont, btn_selected == btn_OK ? selectedColor : normalColor, SpriteEffects.None);
                        btn_Cancel.Draw(spriteBatch, menuItemFont, btn_selected == btn_Cancel ? selectedColor : normalColor, SpriteEffects.None);
                        break;
                    }
                #endregion

                #region DifficultChoose
                case TitleScreenState.DifficultChoose:
                    {
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "Choose your game mode", new Vector2(400, 100), normalColor);
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "WARNING: This value can not be changed during the game",
                            new Vector2(400, 120), normalColor);

                        btn_easy.Draw(spriteBatch, menuItemFont, btn_selected == btn_easy ? selectedColor : normalColor, SpriteEffects.None);
                        btn_normal.Draw(spriteBatch, menuItemFont, btn_selected == btn_normal ? selectedColor : normalColor, SpriteEffects.None);
                        btn_hard.Draw(spriteBatch, menuItemFont, btn_selected == btn_hard ? selectedColor : normalColor, SpriteEffects.None);

                        break;
                    }
                #endregion

                #region ContinueErr
                case TitleScreenState.ContinueErr:
                    {
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "You have no saved game currently",
                            new Vector2(400, 100), normalColor);
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "Press back to return to the title screen",
                            new Vector2(400, 100), normalColor);
                        break;
                    }
                #endregion

                #region QuitPrompt
                case TitleScreenState.QuitPrompt:
                    {
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, "Quit the game?", new Vector2(400, 100), normalColor);

                        btn_OK.Draw(spriteBatch, menuItemFont, btn_selected == btn_OK ? selectedColor : normalColor, SpriteEffects.None);
                        btn_Cancel.Draw(spriteBatch, menuItemFont, btn_selected == btn_Cancel ? selectedColor : normalColor, SpriteEffects.None);
                        break;
                    }
                #endregion

                #region Credits
                case TitleScreenState.Credits:
                    {
                        Fonts.DrawCenteredText(spriteBatch, menuItemFont, credits[currentCreditsItem],
                            new Vector2(400, 120), normalColor * alpha);
                        break;
                    }
                #endregion

                #region Options
                case TitleScreenState.Options:
                    {
                        btn_volum.Text = "Sound volum: " + volum.ToString() + "%";
                        btn_volum.Draw(spriteBatch, menuItemFont, btn_selected == btn_volum ? selectedColor : normalColor, SpriteEffects.None);
                        btn_back.Draw(spriteBatch, menuItemFont, btn_selected == btn_back ? selectedColor : normalColor, SpriteEffects.None);
                        break;
                    }
                #endregion

                #region Help

                case TitleScreenState.Help:
                    Fonts.DrawCenteredText(spriteBatch, menuItemFont,
                        "Move: A S W D\n" +
                        "Attack: Space\n" +
                        "Skill: 1 2 3 4 5 6\n" +
                        "Inventory: I\n" +
                        "Questlog: L\n" +
                        "Skills: K\n" +
                        "Nagivation: Arrow\n" +
                        "Select: Enter\n" +
                        "Return/Back: Escape\n",
                        new Vector2(400, 240), selectedColor * alpha);
                    break;

                #endregion

                default:
                    break;
            }

        }
        #endregion

        #region FlyingObject
        internal class FlyingObject : GameObject
        {
            public FlyingObject(Texture2D texture)
            {
                animations.Add("fly", new AnimationStrip(texture, 1, 1, "fly"));
                worldLocation = new Vector2(RandomHelper.rand.Next((int)Camera.ViewPort.X,
                                 (int)Camera.ViewPort.X + Camera.ViewPort.Width), 470);
                velocity = new Vector2(-(float)RandomHelper.rand.NextDouble(), -1f);
                velocity *= RandomHelper.rand.Next(20, 100);
                scale += (float)RandomHelper.rand.NextDouble() - 0.5f;
                affectColor = Color.White * (float)(RandomHelper.rand.NextDouble() + 0.5f);
                drawDepth = 1f;
                enabled = true;
                PlayAnimation("fly", false, true, false);
            }

            public override void Update(GameTime gameTime)
            {
                if (worldLocation.X <= 0 || worldLocation.Y <= 0)
                    enabled = false;

                base.Update(gameTime);
            }
        }
        #endregion
    }
}
